<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>工具管理系统</title>
    <style>
        :root {
            --bg-color: #ffffff;
            --text-color: #333333;
            --border-color: #e0e0e0;
            --card-bg: #ffffff;
            --card-shadow: 0 2px 8px rgba(0,0,0,0.1);
            --primary-color: #007bff;
            --secondary-color: #6c757d;
            --success-color: #28a745;
            --danger-color: #dc3545;
            --input-bg: #ffffff;
            --input-border: #ced4da;
        }

        [data-theme="dark"] {
            --bg-color: #1a1a1a;
            --text-color: #e0e0e0;
            --border-color: #404040;
            --card-bg: #2d2d2d;
            --card-shadow: 0 2px 8px rgba(0,0,0,0.3);
            --primary-color: #0066cc;
            --secondary-color: #5a6268;
            --success-color: #218838;
            --danger-color: #c82333;
            --input-bg: #404040;
            --input-border: #606060;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            background-color: var(--bg-color);
            color: var(--text-color);
            transition: all 0.3s ease;
            line-height: 1.6;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }

        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
            padding: 20px 0;
            border-bottom: 1px solid var(--border-color);
        }

        .header h1 {
            font-size: 28px;
            font-weight: 600;
        }

        .theme-toggle {
            background: none;
            border: 1px solid var(--border-color);
            padding: 8px 12px;
            border-radius: 20px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.3s ease;
            color: var(--text-color);
        }

        .theme-toggle:hover {
            background-color: var(--border-color);
        }

        .add-btn {
            background-color: var(--primary-color);
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 6px;
            cursor: pointer;
            font-size: 16px;
            margin-bottom: 20px;
        }

        .add-btn:hover {
            opacity: 0.9;
        }

        .tools-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
            gap: 20px;
        }

        .tool-card {
            background-color: var(--card-bg);
            border: 1px solid var(--border-color);
            border-radius: 8px;
            padding: 20px;
            box-shadow: var(--card-shadow);
            transition: transform 0.2s ease;
        }

        .tool-card:hover {
            transform: translateY(-2px);
        }

        .tool-header {
            display: flex;
            justify-content: space-between;
            align-items: start;
            margin-bottom: 15px;
        }

        .tool-title {
            font-size: 18px;
            font-weight: 600;
            margin-bottom: 5px;
        }

        .tool-actions {
            display: flex;
            gap: 8px;
        }

        .btn-small {
            padding: 4px 8px;
            font-size: 12px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            transition: opacity 0.2s ease;
        }

        .btn-edit {
            background-color: var(--secondary-color);
            color: white;
        }

        .btn-delete {
            background-color: var(--danger-color);
            color: white;
        }

        .btn-small:hover {
            opacity: 0.8;
        }

        .tool-code {
            background-color: var(--input-bg);
            border: 1px solid var(--input-border);
            border-radius: 4px;
            padding: 10px;
            font-family: 'Courier New', monospace;
            font-size: 14px;
            margin: 10px 0;
            overflow-x: auto;
        }

        .tool-stats {
            display: flex;
            gap: 15px;
            font-size: 14px;
            color: var(--secondary-color);
        }

        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
            z-index: 1000;
            overflow-y: auto;
        }

        .modal-content {
            position: relative;
            margin: 50px auto;
            background-color: var(--card-bg);
            border-radius: 8px;
            padding: 30px;
            width: 90%;
            max-width: 500px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.3);
            max-height: 90vh;
            overflow-y: auto;
        }

        .form-group {
            margin-bottom: 15px;
        }

        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: 500;
        }

        .form-group input,
        .form-group textarea {
            width: 100%;
            padding: 8px 12px;
            border: 1px solid var(--input-border);
            border-radius: 4px;
            background-color: var(--input-bg);
            color: var(--text-color);
            font-size: 14px;
        }

        .form-group textarea {
            min-height: 100px;
            resize: vertical;
        }

        .form-actions {
            display: flex;
            gap: 10px;
            justify-content: flex-end;
            margin-top: 20px;
        }

        .btn-primary {
            background-color: var(--primary-color);
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 4px;
            cursor: pointer;
        }

        .btn-secondary {
            background-color: var(--secondary-color);
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 4px;
            cursor: pointer;
        }

        .toggle-btn {
            padding: 8px 16px;
            font-size: 13px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            transition: all 0.2s ease;
            font-weight: 600;
            min-width: 60px;
        }

        .btn-enable {
            background-color: var(--success-color);
            color: white;
        }

        .btn-enable:hover {
            background-color: #218838;
        }

        .btn-disable {
            background-color: var(--danger-color);
            color: white;
        }

        .btn-disable:hover {
            background-color: #c82333;
        }

        .tool-card.disabled {
            opacity: 0.6;
            filter: grayscale(0.3);
        }

        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: var(--secondary-color);
        }

        .empty-state h3 {
            margin-bottom: 10px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <button class="theme-toggle" onclick="toggleTheme()">🌓 切换主题</button>
        </div>
        
        <div style="display: flex; gap: 20px; align-items: center; margin-bottom: 20px; flex-wrap: wrap;">
            <button class="add-btn" onclick="openModal()">+ 添加新工具</button>
            
            <div style="display: flex; gap: 10px; align-items: center;">
                <label>排序:</label>
                <select id="sort-select" onchange="applyFilters()" style="padding: 8px; border-radius: 4px; border: 1px solid var(--input-border); background-color: var(--input-bg); color: var(--text-color);">
                    <option value="default">默认排序</option>
                    <option value="success_rate_desc">成功率 ↓</option>
                    <option value="success_rate_asc">成功率 ↑</option>
                    <option value="total_calls_desc">调用总量 ↓</option>
                    <option value="total_calls_asc">调用总量 ↑</option>
                </select>
            </div>
            
            <div style="display: flex; gap: 10px; align-items: center;">
                <label>提供方:</label>
                <select id="provider-filter" onchange="applyFilters()" style="padding: 8px; border-radius: 4px; border: 1px solid var(--input-border); background-color: var(--input-bg); color: var(--text-color);">
                    <option value="all">全部</option>
                </select>
            </div>
        </div>
        
        <div id="tools-container">
            <!-- 工具卡片将在这里动态加载 -->
        </div>
    </div>

    <!-- 模态框 -->
    <div id="modal" class="modal">
        <div class="modal-content">
            <h2 id="modal-title">添加新工具</h2>
            <form id="tool-form">
                <input type="hidden" id="tool-id">
                
                <div class="form-group">
                    <label for="description">描述</label>
                    <input type="text" id="description" required>
                </div>
                
                <div class="form-group">
                    <label for="code">代码</label>
                    <textarea id="code" required></textarea>
                </div>
                
                <div class="form-group">
                    <label for="successes">成功次数</label>
                    <input type="number" id="successes" min="0" value="0">
                </div>
                
                <div class="form-group">
                    <label for="failures">失败次数</label>
                    <input type="number" id="failures" min="0" value="0">
                </div>
                
                <div class="form-group">
                    <label for="success-rate">成功率</label>
                    <input type="text" id="success-rate" placeholder="例如: 0.95">
                </div>
                
                <div class="form-group">
                    <label for="provider">提供方</label>
                    <input type="text" id="provider" placeholder="例如: 系统管理员">
                </div>
                
                <div class="form-group">
                    <label>
                        <input type="checkbox" id="enabled" checked> 启用状态
                    </label>
                </div>
                
                <div class="form-actions">
                    <button type="button" class="btn-secondary" onclick="closeModal()">取消</button>
                    <button type="submit" class="btn-primary">保存</button>
                </div>
            </form>
        </div>
    </div>

    <script>
        // 主题切换
        function toggleTheme() {
            const html = document.documentElement;
            const currentTheme = html.getAttribute('data-theme');
            const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
            html.setAttribute('data-theme', newTheme);
            localStorage.setItem('theme', newTheme);
        }

        // 加载保存的主题
        const savedTheme = localStorage.getItem('theme') || 'light';
        document.documentElement.setAttribute('data-theme', savedTheme);

        let allTools = [];

        // 加载工具数据
        async function loadTools() {
            try {
                const response = await fetch('/api/tools');
                allTools = await response.json();
                updateProviderFilter(allTools);
                applyFilters();
            } catch (error) {
                console.error('加载工具失败:', error);
            }
        }

        // 更新提供方筛选器
        function updateProviderFilter(tools) {
            const providers = [...new Set(tools.map(tool => tool.provider || '未知'))];
            const providerSelect = document.getElementById('provider-filter');
            
            // 保留"全部"选项
            providerSelect.innerHTML = '<option value="all">全部</option>';
            
            providers.forEach(provider => {
                const option = document.createElement('option');
                option.value = provider;
                option.textContent = provider;
                providerSelect.appendChild(option);
            });
        }

        // 应用排序和筛选
        function applyFilters() {
            let filteredTools = [...allTools];
            
            // 应用提供方筛选
            const providerFilter = document.getElementById('provider-filter').value;
            if (providerFilter !== 'all') {
                filteredTools = filteredTools.filter(tool => 
                    (tool.provider || '未知') === providerFilter
                );
            }
            
            // 应用排序
            const sortOption = document.getElementById('sort-select').value;
            switch (sortOption) {
                case 'success_rate_desc':
                    filteredTools.sort((a, b) => parseFloat(b.success_rate || 0) - parseFloat(a.success_rate || 0));
                    break;
                case 'success_rate_asc':
                    filteredTools.sort((a, b) => parseFloat(a.success_rate || 0) - parseFloat(b.success_rate || 0));
                    break;
                case 'total_calls_desc':
                    filteredTools.sort((a, b) => (b.total_calls || 0) - (a.total_calls || 0));
                    break;
                case 'total_calls_asc':
                    filteredTools.sort((a, b) => (a.total_calls || 0) - (b.total_calls || 0));
                    break;
                default:
                    // 默认按ID排序
                    filteredTools.sort((a, b) => a.id - b.id);
            }
            
            renderTools(filteredTools);
        }

        // 渲染工具列表
        function renderTools(tools) {
            const container = document.getElementById('tools-container');
            
            if (tools.length === 0) {
                container.innerHTML = `
                    <div class="empty-state">
                        <h3>暂无工具</h3>
                        <p>点击"添加新工具"按钮创建第一个工具</p>
                    </div>
                `;
                return;
            }

            container.innerHTML = '';
            container.className = 'tools-grid';
            
            tools.forEach(tool => {
                const card = document.createElement('div');
                card.className = `tool-card ${tool.enabled ? '' : 'disabled'}`;
                card.innerHTML = `
                    <div class="tool-header">
                        <div>
                            <div class="tool-title">${tool.description}</div>
                        </div>
                        <div class="tool-actions">
                            <button class="btn-small btn-edit" onclick="editTool(${tool.id})">编辑</button>
                            <button class="btn-small btn-delete" onclick="deleteTool(${tool.id})">删除</button>
                        </div>
                    </div>
                    <div class="tool-code">${escapeHtml(tool.code)}</div>
                    <div style="margin-bottom: 10px; font-size: 14px; color: var(--secondary-color);">
                    👤 提供方: ${tool.provider || '未知'}
                </div>
                <div class="tool-stats">
                    <span>✅ ${tool.number_of_successes || 0}</span>
                    <span>❌ ${tool.number_of_failures || 0}</span>
                    <span>📊 ${tool.success_rate || 'N/A'}</span>
                    <span>📈 调用总量: ${tool.total_calls || 0}</span>
                </div>
                <div style="display: flex; justify-content: space-between; align-items: center; margin-top: 15px; padding: 10px; background-color: rgba(0,0,0,0.05); border-radius: 4px;">
                    <span style="font-size: 14px; font-weight: 600; color: var(--text-color);">
                        状态: ${tool.enabled ? '🟢 启用' : '🔴 禁用'}
                    </span>
                    <button class="toggle-btn ${tool.enabled ? 'btn-disable' : 'btn-enable'}" 
                            onclick="toggleTool(${tool.id}, ${tool.enabled})"
                            style="box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
                        ${tool.enabled ? '禁用' : '启用'}
                    </button>
                </div>
                `;
                container.appendChild(card);
            });
        }

        // HTML转义
        function escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }

        // 模态框控制
        function openModal(tool = null) {
            const modal = document.getElementById('modal');
            const form = document.getElementById('tool-form');
            const title = document.getElementById('modal-title');
            
            if (tool) {
                title.textContent = '编辑工具';
                document.getElementById('tool-id').value = tool.id;
                document.getElementById('description').value = tool.description;
                document.getElementById('code').value = tool.code;
                document.getElementById('successes').value = tool.number_of_successes || 0;
                document.getElementById('failures').value = tool.number_of_failures || 0;
                document.getElementById('success-rate').value = tool.success_rate || '';
                document.getElementById('provider').value = tool.provider || '未知';
                document.getElementById('enabled').checked = tool.enabled !== false; // 默认启用
            } else {
                title.textContent = '添加新工具';
                form.reset();
                document.getElementById('tool-id').value = '';
            }
            
            modal.style.display = 'block';
            document.body.style.overflow = 'hidden'; // 防止背景滚动
            
            // 聚焦到第一个输入框
            setTimeout(() => {
                document.getElementById('description').focus();
            }, 100);
        }

        function closeModal() {
            document.getElementById('modal').style.display = 'none';
            document.body.style.overflow = ''; // 恢复背景滚动
        }

        // 表单提交
        document.getElementById('tool-form').addEventListener('submit', async (e) => {
            e.preventDefault();
            
            const toolId = document.getElementById('tool-id').value;
            const successes = parseInt(document.getElementById('successes').value) || 0;
            const failures = parseInt(document.getElementById('failures').value) || 0;
            
            const toolData = {
                description: document.getElementById('description').value,
                code: document.getElementById('code').value,
                number_of_successes: successes,
                number_of_failures: failures,
                success_rate: document.getElementById('success-rate').value,
                provider: document.getElementById('provider').value || '未知',
                total_calls: successes + failures,
                enabled: document.getElementById('enabled').checked
            };

            try {
                let response;
                if (toolId !== '') {
                    response = await fetch(`/api/tools/${toolId}`, {
                        method: 'PUT',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify(toolData)
                    });
                } else {
                    response = await fetch('/api/tools', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify(toolData)
                    });
                }

                if (response.ok) {
                    closeModal();
                    loadTools();
                }
            } catch (error) {
                console.error('保存工具失败:', error);
            }
        });

        // 编辑工具
        async function editTool(id) {
            try {
                const response = await fetch('/api/tools');
                const tools = await response.json();
                const tool = tools.find(t => t.id === id);
                if (tool) {
                    openModal(tool);
                }
            } catch (error) {
                console.error('加载工具失败:', error);
            }
        }

        // 删除工具
        async function deleteTool(id) {
            if (confirm('确定要删除这个工具吗？')) {
                try {
                    const response = await fetch(`/api/tools/${id}`, {
                        method: 'DELETE'
                    });
                    
                    if (response.ok) {
                        loadTools();
                    }
                } catch (error) {
                    console.error('删除工具失败:', error);
                }
            }
        }

        // 点击模态框背景关闭
        document.getElementById('modal').addEventListener('click', function(event) {
            if (event.target === this) {
                closeModal();
            }
        });

        // ESC键关闭模态框
         document.addEventListener('keydown', function(event) {
             if (event.key === 'Escape') {
                 const modal = document.getElementById('modal');
                 if (modal.style.display === 'block') {
                     closeModal();
                 }
             }
         });

         // 启用/禁用工具
         async function toggleTool(toolId, currentEnabled) {
             try {
                 const response = await fetch('/api/tools');
                 const tools = await response.json();
                 const tool = tools.find(t => t.id === toolId);
                 
                 if (tool) {
                     const updatedTool = {
                         ...tool,
                         enabled: !currentEnabled
                     };
                     
                     const updateResponse = await fetch(`/api/tools/${toolId}`, {
                         method: 'PUT',
                         headers: { 'Content-Type': 'application/json' },
                         body: JSON.stringify(updatedTool)
                     });
                     
                     if (updateResponse.ok) {
                         loadTools(); // 重新加载工具列表
                     }
                 }
             } catch (error) {
                 console.error('切换工具状态失败:', error);
             }
         }

        // 页面加载时加载工具
        loadTools();
    </script>
</body>
</html>